package com.data.mining.project;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class Searcher
{

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main( String[ ] args) throws Exception
	{
		if ( args.length != 2)
			throw new Exception( "Usage: java " + Searcher.class.getName( )
					+ " <index dir> <query>");

		File indexDir = new File( args[0]);
		String query = new String( args[1]);

		if ( !indexDir.exists( ) || !indexDir.isDirectory( ))
		{
			throw new IOException( indexDir
					+ " does not exist os is not directory");
		}

		search( indexDir, query);
	}

	private static void search( File indexDir, String query)
			throws IOException, ParseException
	{
		Directory fsDir = FSDirectory.getDirectory( indexDir, false);
		IndexSearcher searcher = new IndexSearcher( fsDir);

		TermQuery termQuery = new TermQuery( new Term( "content", query));

		long start = new Date( ).getTime( );
		TopDocs hits = searcher.search( termQuery, null, 10);
		long end = new Date( ).getTime( );

		System.out.println( "Searching files took " + ( ( end - start) / 60)
				+ " seconds");
		System.out.println( hits.totalHits);
		for ( ScoreDoc document : hits.scoreDocs)
		{
			System.out.println( searcher.doc( document.doc).getField(
					"url").stringValue( ));
		}
	}

}
